<template>
    <page-dialog
      :title="dialogInfo.title"
      v-model:visible="shows"
      :width="dialogInfo.width"
      :bt-list="dialogInfo.btList"
    >
      <!-- 条件栏 -->
      <page-filter
        v-model:query="filterInfo.query.queryMap"
        :query-more-json="true"
        :filter-list="filterInfo.searchList"
        :filter-btn="filterInfo.searchBtn"
      >
        <template v-slot:filter-supplierProdct>
          <slip-select
            v-model="filterInfo.query.queryParams.notDefaultProductSupplierId"
            value-key="value"
            placeholder="选择供货供应商"
            :api="supplierInfo.api"
            v-model:query="supplierInfo.query"
            key-field="supplierName"
            value-field="supplierId"
            :clearable="true"
            :filterable="true"
            :multiple="true"
            @change="search"
          />
        </template>
      </page-filter>
      <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
        <dialog-table
          ref="resourceTable"
          :refresh="tableInfo.refresh"
          :init-curpage="tableInfo.initCurpage"
          v-model:data="tableInfo.data"
          :api="tableInfo.api"
          v-model:query="filterInfo.query"
          :field-list="tableInfo.fieldList"
          :handle="tableInfo.handle"
          :rowKey="rowKey"
          :highlight-row="highlightRow"
          :checkedRowList="checkedRowList"
          :reserve-selection="true"
          :check-box="checkBox"
          @handleEvent="handleEvent"
        >
          <template v-slot:col-editQty="scope">
            <el-form-item
              v-if="scope.row.qtyOperateMode !== 3"
              class="margin-bottom"
              @click.stop.native=""
            >
              <div class="page-table-input-number-wrapper">
                <div class="page-table-input-number-left">
                  <div class="page-table-input-number-item">
                    <el-form-item>
                      <el-input-number
                        v-model.lazy="scope.row.largeUnitQty"
                        style="width: 100%; margintop: 18px"
                        clearable
                        controls-position="right"
                        :precision="
                          scope.row.qtyOperateMode === 0 ||
                          scope.row.qtyOperateMode === 2
                            ? 0
                            : systemConfig.qty_show_precision
                        "
                        :min="0"
                        :max="99999999"
                      />
                    </el-form-item>
                    <div class="page-table-input-number-item-unite">
                      {{ scope.row.networkUnit }}
                    </div>
                  </div>
                  <div
                    v-if="
                      scope.row.unitConvertCoefficient > 1 &&
                      scope.row.qtyOperateMode === 2
                    "
                    class="page-table-input-number-item"
                  >
                    <el-form-item>
                      <el-input-number
                        v-model.lazy="scope.row.smallUnitQty"
                        style="width: 100%; margintop: 18px"
                        clearable
                        controls-position="right"
                        :precision="0"
                        :min="0"
                        :max="scope.row.unitConvertCoefficient - 1"
                      />
                    </el-form-item>
                    <div class="page-table-input-number-item-unite">
                      {{ scope.row.calcUnitName }}
                    </div>
                  </div>
                </div>
              </div>
            </el-form-item>
            <span v-else>{{ $fn.qtyFormatter(scope.row.editQty) }}</span>
          </template>
          <template v-slot:col-distributeCount="scope">
            <span v-if="scope.row.distributeCount">
              {{ scope.row.distributeCount + scope.row.networkUnit }}
            </span>
            <span v-else>-</span>
          </template>
          <template v-slot:col-warehouseCount="scope">
            <span v-if="scope.row.warehouseCount">
              {{ scope.row.warehouseCount + scope.row.networkUnit }}
            </span>
            <span v-else>-</span>
          </template>
          <template v-slot:col-qty="scope">
            <span v-if="scope.row.qty">
              {{ scope.row.qty + scope.row.networkUnit }}
            </span>
            <span v-else>-</span>
          </template>
        </dialog-table>
      </el-form>
    </page-dialog>
  </template>
  <script setup name="newSelectProduct">
  import PageDialog from '@/components/PageDialog/index'
  import DialogTable from '@/components/DialogTable/index'
  import PageFilter from '@/components/NewPageFilter/index'
  import SlipSelect from '@/components/SlipSelect/index'
  import { getCustomizeSetting } from '@/api/customize'
  import { getProductCustomizeList, getSupplierAll } from '@/api/core.js'
  
  const { proxy } = getCurrentInstance()
  const emits = defineEmits()
  const props = defineProps({
    highlightRow: {
      type: Boolean,
      default: false,
    },
    checkBox: {
      type: Boolean,
      default: true,
    },
    rowKey: {
      type: String,
      default: 'id',
    },
    api: {
      type: Function,
      default: getProductCustomizeList,
    },
    showDialog: {
      type: Boolean,
      default: false,
    },
    showPrice: {
      type: Boolean,
    },
    showSupplierName: {
      type: Boolean,
      default: false,
    },
    notDefaultProductSupplier: {
      //是否供货供应商赛选
      type: Boolean,
      default: true,
    },
    query: {
      type: Object,
      default: function () {
        return {}
      },
    },
    queryParams: {
      type: Object,
      default: function () {
        return {}
      },
    },
    showStock: {
      type: Boolean,
      default: false,
    },
    tableKey: {
      type: String,
      default:
        'productPageWithDefaultSupplier-com.slip.spd.entity.vo.core.CoreProductVONew',
    },
    checkedList: {
      type: Array,
      default: () => {
        return []
      },
    },
    checkedRowList: {
      type: Array,
      default: () => {
        return []
      },
    },
    saveEmpty: {
      type: Boolean,
      default: false,
    },
    showEditQty: {
      type: Boolean,
      default: true,
    },
  })
  
  const systemConfig = ref(proxy.$store.state.permission.systemConfig)
  const supplierInfo = ref({
    api: getSupplierAll,
    query: {
      supplierAuth: 'supplierId',
      sort: 'create_time desc',
    },
  })
  // 过滤相关配置
  const filterInfo = ref({
    query: {
      page: true,
      customizeUserVO: {},
      sortString: proxy.sortString,
      queryMap: {
        // type: {
        //   asTbName: 'core_product_new',
        //   columnName: 'type',
        //   queryResource: 0,
        //   queryType: 'EQUALS',
        //   queryCategory: 'AND',
        //   value: 0,
        // },
      },
      queryParams: {},
    },
    searchList: [],
    searchBtn: [{ type: 'button', label: '搜索', event: search }],
  })
  // 表格相关
  const tableInfo = ref({
    refresh: 1,
    initCurpage: 1,
    data: [],
    api: undefined,
    fieldList: [],
  })
  // 弹窗相关
  const dialogInfo = ref({
    title: '选择产品',
    width: '90%',
    btLoading: false,
    btList: [
      { label: '关闭', event: handleClose, show: true },
      {
        label: '保存',
        type: 'primary',
        disabled: !props.saveEmpty,
        event: save,
        show: true,
      },
    ],
  })
  const selectRow = ref([])
  
  const shows = computed({
    get() {
      return props.showDialog
    },
    set(newValue) {
      emits('update:showDialog', newValue) // 更新父组件shows
    },
  })
  
  watch(
    () => tableInfo.value.data,
    () => {
      tableInfo.value.data.forEach((row) => {
        let smallUnitQty = parseFloat(row.smallUnitQty || 0)
        let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
        let largeUnitQty = parseFloat(row.largeUnitQty || 0)
        let editCalcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
          smallUnitQty
        )
        let editQty = proxy.$fn.qtyFormatter(
          proxy.$fn.accDiv(editCalcQty, unitConvertCoefficient)
        )
        row.editCalcQty = editCalcQty
        row.editQty = editQty
        row.sumAmount = proxy.$fn.accMul(
          proxy.$fn.accAdd(
            proxy.$fn.accDiv(smallUnitQty, unitConvertCoefficient),
            largeUnitQty
          ),
          parseFloat(row.price)
        )
      })
    },
    {
      deep: true,
    }
  )
  
  setData()
  function setData() {
    let obj = {
      price: {
        label: '单价',
        value: 'price',
        hidden: true,
        type: 'column',
        show: false,
        permission: !props.showPrice,
        formatter: proxy.$fn.TripartiteMethod,
      },
      defaultSupplierPrice: {
        label: '默认供应商价格',
        value: 'defaultSupplierPrice',
        type: 'column',
        permission: !props.showPrice,
        show: false,
        formatter: proxy.$fn.TripartiteMethod,
        hidden: true,
      },
      showPrice: {
        label: '展示价格',
        value: 'showPrice',
        type: 'column',
        show: false,
        permission: !props.showPrice,
        formatter: proxy.$fn.TripartiteMethod,
        hidden: true,
      },
      commonName: {
        label: '通用名称',
        value: 'commonName',
        componentType: 'input',
        show: false,
        hidden: true,
      },
      orderNo: {
        label: '收货单单号',
        value: 'orderNo',
        componentType: 'number',
        show: false,
        hidden: true,
      },
      editQty: {
        label: '数量',
        value: 'editQty',
        type: 'slot',
        componentType: 'number',
        show: false,
        hidden: true,
        minWidth: '250px',
      },
      distributeCount: {
        label: '配送数量',
        value: 'distributeCount',
        type: 'slot',
        hidden: true,
      },
      warehouseCount: {
        label: '收货数量',
        value: 'warehouseCount',
        type: 'slot',
        hidden: true,
      },
      qty: {
        label: '省采数量',
        value: 'qty',
        type: 'slot',
        hidden: true,
      },
    }
    tableInfo.value.fieldList = Object.values({
      ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
      ...proxy.$fn.deepClone(obj),
    })
    filterInfo.value.searchList = Object.values({
      ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
      ...proxy.$fn.deepClone(obj),
    })
    getCustomize()
  }
  // 获取列表
  function getList() {
    tableInfo.value.refresh = Math.random()
  }
  function search() {
    tableInfo.value.initCurpage = Math.random()
    tableInfo.value.refresh = Math.random()
  }
  function save() {
    console.log(selectRow.value)
    console.log(selectRow.value && selectRow.value.length)
    if (selectRow.value && selectRow.value.length) {
      selectRow.value.forEach((item) => {
        item.calcQty = item.editCalcQty
        item.qty = item.editQty
      })
    }
    handleClose()
    emits('callback', selectRow.value)
  }
  function handleEvent(event, data) {
    switch (event) {
      case 'tableClickRow':
        selectRow.value = data
        if (!props.saveEmpty) {
          dialogInfo.value.btList[1].disabled = !selectRow.value
        }
        break
      case 'tableCheck':
        selectRow.value = data
        if (!props.saveEmpty) {
          dialogInfo.value.btList[1].disabled = !selectRow.value
        }
        break
    }
  }
  // 关闭弹窗前的回调
  function handleClose() {
    shows.value = false
    emits('reset')
  }
  function getCustomize() {
    let param = { tableKey: props.tableKey }
    getCustomizeSetting(param).then((res) => {
      if (res && res.success) {
        let data = res.data
        tableInfo.value.fieldList = proxy.$fn.setFieldList(
          tableInfo.value.fieldList,
          data.detail
        )
        if (!props.showEditQty) {
          tableInfo.value.fieldList.forEach((item) => {
            if (item.value === 'editQty') {
              item.hidden = true
            }
          })
        }
        console.log(tableInfo.value.fieldList)
        let searchInfo = proxy.$fn.setSearchList(
          filterInfo.value.searchList,
          data.detail
        )
        let supplierProdct = {
          slot: true,
          value: 'supplierProdct',
        }
        if (props.notDefaultProductSupplier) {
          filterInfo.value.searchList =
            searchInfo.searchList.concat(supplierProdct)
        } else {
          filterInfo.value.searchList = searchInfo.searchList
        }
        filterInfo.value.searchList.forEach((item) => {
          item.event = search
        })
        console.log(filterInfo.value.searchList)
        filterInfo.value.query.customizeUserVO = data
        filterInfo.value.query.queryMap = {
          ...searchInfo.queryMap,
          ...props.query,
          ...filterInfo.value.query.queryMap,
        }
        filterInfo.value.query.queryParams = {
          ...filterInfo.value.query.queryParams,
          ...props.queryParams,
        }
        tableInfo.value.api = props.api
        getList()
      }
    })
  }
  </script>
  
  <style scoped lang="scss"></style>
  